﻿using Donal.Xms.API.OAuth;
using Donal.Xms.Common;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace Donal.Xms.Web.api.oauth.weixin
{
    public partial class return_uri : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            //获取code码，以获取openid和access_token
            string code = DTRequest.GetQueryString("code");

            string duid = DTRequest.GetQueryString("duid");

            //检查参数是否正确
            if (string.IsNullOrEmpty(code))
            {
                Response.Redirect(new Web.UI.BasePage().linkurl(0,"error", "?msg=" + Utils.UrlEncode("出错了，获取CODE回调参数有误！")));
                return;
            }


            //获取openid及access_token的url
            try
            {
                //获得配置信息
                oauth_config oauth_config = oauth_helper.get_config(4);
                if (oauth_config == null)
                {
                    HttpContext.Current.Response.Redirect(new Web.UI.BasePage().linkurl(0,"error", "?msg=出错了，您尚未配置微信的API信息！"));
                    return;
                }

                //第一步：获取Access Token
                Dictionary<string, object> dic = weixin_helper.get_access_token(oauth_config.oauth_app_id, oauth_config.oauth_app_key, oauth_config.return_uri, code);
                if (dic == null || !dic.ContainsKey("access_token"))
                {
                    Response.Redirect(new Web.UI.BasePage().linkurl(0,"error", "?msg=出错了，无法获取Access Token，请检查App Key是否正确！"));
                    return;
                }

                string oauth_access_token = dic["access_token"].ToString();
                string oauth_openid = dic["openid"].ToString();

                Dictionary<string, object> user_info_dic = weixin_helper.get_info(oauth_access_token, oauth_openid);
                if (user_info_dic == null)
                {
                    Response.Redirect(new Web.UI.BasePage().linkurl(0,"error", "?msg=出错啦，无法获取授权用户信息！\"}"));
                    return;
                }

                //绑定到对应的授权类型
                Model.user_oauth oauthModel = new BLL.user_oauth().GetModel("weixin", user_info_dic["openid"].ToString());

                if (oauthModel != null)
                {
                    oauthModel.avatar = user_info_dic["headimgurl"].ToString();
                    oauthModel.sex = user_info_dic["sex"].ToString() == "1" ? "男" : user_info_dic["sex"].ToString() == "2" ? "女" : "保密";

                    oauthModel.nick = user_info_dic["nickname"].ToString();
                    oauthModel.oauth_name = "weixin";
                    oauthModel.oauth_access_token = oauth_access_token;
                    oauthModel.oauth_openid = user_info_dic["openid"].ToString();

                    oauthModel.login_tags = duid;

                    new BLL.user_oauth().Update(oauthModel);

                    Model.users user = new BLL.users().GetModel(oauthModel.user_id);

                    if (user != null)
                    {
                        HttpContext.Current.Session[DTKeys.SESSION_USER_INFO] = user;

                        HttpContext.Current.Response.Redirect(Utils.GetCookie(DTKeys.COOKIE_URL_REFERRER));

                        return;
                    }
                    else
                    {
                        HttpContext.Current.Response.Redirect(new Donal.Xms.Web.UI.BasePage().linkurl(0,"weixin_login", "bind", duid));
                    }
                }
                else
                {
                    oauthModel = new Model.user_oauth();
                    oauthModel.avatar = user_info_dic["headimgurl"].ToString();
                    oauthModel.sex = user_info_dic["sex"].ToString() == "1" ? "男" : user_info_dic["sex"].ToString() == "2" ? "女" : "保密";

                    oauthModel.nick = user_info_dic["nickname"].ToString();
                    oauthModel.oauth_name = "weixin";
                    oauthModel.oauth_access_token = oauth_access_token;
                    oauthModel.oauth_openid = user_info_dic["openid"].ToString();

                    oauthModel.login_tags = duid;

                    oauthModel.user_id = 0;
                    oauthModel.user_name = string.Empty;

                    new BLL.user_oauth().Add(oauthModel);

                    HttpContext.Current.Response.Redirect(new Donal.Xms.Web.UI.BasePage().linkurl(0,"weixin_login", "bind", duid));
                }
            }
            catch (Exception ex)
            {
                throw new Exception(ex.ToString());
            }


        }
    }
}